package dao

import (
	"errors"
	"go-shop-demo/app/common"
	"go-shop-demo/app/consts"
	"go-shop-demo/app/dto"
	"go-shop-demo/app/model"
)

func AddOrd(order model.Order, ord []dto.OrderGoodsDto) (id uint, err error) {
	tx := common.GetTx()
	err = tx.Create(&order).Error
	if err != nil {
		tx.Rollback()
		return 0, err
	}
	for _, res := range ord {
		ordergoods := model.OrderGoods{GoodsName: res.GoodsName, OrderId: order.ID, GoodNum: res.GoodNum}
		err = tx.Create(&ordergoods).Error
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}
	tx.Commit()
	return order.ID, nil
}

func CheckOrder(id uint) error {
	db := common.GetDB()
	order := model.Order{}
	err := db.Where("id = ?", id).First(&order).Error
	if err != nil {
		return errors.New("订单不存在")
	}
	if order.Status == 1 {
		return errors.New("订单已支付")
	}
	return nil
}

func DeleteOrder(id uint) {
	tx := common.GetDB()
	err := tx.Delete(&model.Order{}, id).Error
	common.CheckErr(err, consts.ServerError, "")
	return
}

func DetailOrd(detail dto.DetailOrderDto) (result []model.RespOder, err error) {
	db := common.GetDB()
	var orders []model.Order
	err = db.Where("user_name = ? AND status = ?", detail.UserName, detail.Status).Find(&orders).Error
	if err != nil {
		return result, err
	}
	for _, order := range orders {
		ordergoods := model.OrderGoods{}
		err = db.Where("order_id = ?", order.ID).First(&ordergoods).Error
		if err != nil {
			continue
		}
		respoder := model.RespOder{order, ordergoods}
		result = append(result, respoder)
	}
	return result, nil

}

func UpdatePay(id uint) bool {
	var order model.Order
	tx := common.GetTx()
	order.ID = id
	err := tx.Model(&order).Update("status", 1).Error
	common.CheckErr(err, consts.ServerError, "")
	return true
}

func DeleteOrderGoodsByOrderId(orderId uint) {
	tx := common.GetTx()
	ordergoods := model.OrderGoods{}
	err := tx.Where("order_id = ?", orderId).Delete(&ordergoods).Error
	common.CheckErr(err, consts.ServerError, "")
}
